import QQMapWX from './map';
const app = getApp();
let Location = null;
let areaList = [];
let qqmap = null;
let area = null;

/**
 * 微信授权
 * @returns {Promise<unknown>}
 */
export const getLocation = () => new Promise((resolve, reject) => {
  if (Location === null) {
    xhs.getFuzzyLocation({
      success(res) {
        Location = res;
        resolve(res);
      },
      fail() {
        xhs.hideLoading();
        xhs.showModal({
          title: '温馨提示',
          content: '小程序将获取您的授权用来显示位置信息',
          success(res) {
            if (res.confirm) {
              xhs.openSetting({
                success(res) {
                  res.authSetting = {
                    'scope.userInfo': true,
                    'scope.userLocation': true
                  };
                }
              });
            } else {
              reject('获取用户位置失败');
            }
          }
        });
      }
    });
  } else {
    resolve(Location);
  }
});

/**
 * 根据经纬拿省市区名
 * @returns {Promise<unknown>}
 */
export const getCityName = () => new Promise((resolve, reject) => {
  if (area) {
    resolve(area);
  } else {
    getLocation().then(res => {
      if (!qqmap) qqmap = new QQMapWX({
        key: 'YZMBZ-CFZHP-ZZODK-L5FUQ-A6GY6-QVB7V'
      });
      qqmap.reverseGeocoder({
        location: {
          latitude: res.latitude,
          longitude: res.longitude
        },
        success(res) {
          const ad_info = res.result.ad_info;
          area = [ad_info.province, ad_info.city, ad_info.district, ad_info.location];
          resolve(area);
        },
        fail: reject
      });
    }, reject);
  }
});

/**
 * 拿所有的省市区CODE
 * @returns {Promise<unknown>}
 */
export const getAreaList = () => new Promise((resolve, reject) => {
  if (areaList.length) {
    resolve(areaList);
  } else {
    app.$getData('/site/address-list').then(data => {
      if (Array.isArray(data.data)) {
        areaList = data.data;
        resolve(data.data);
      } else {
        reject('获取城市列表失败');
      }
    });
  }
});

/**
 * 根据省市区的value拿value 异步
 * @param provinceName
 * @param cityName
 * @param areaName
 * @param getKey
 * @param compareKey
 * @returns {Promise<unknown>}
 */
export const cityKey2Key = (...params) => getAreaList().then(() => key2keySync(...params));

/**
 * 根据省市区的value拿value 同步
 * @param provinceName
 * @param cityName
 * @param areaName
 * @param getKey
 * @param compareKey
 * @returns {[]}
 */
const key2keySync = ([provinceName, cityName, areaName], getKey = 'id', compareKey = 'name') => {
  let areaArr = [];
  areaList.find(province => {
    if (province[compareKey] === provinceName) {
      if (cityName) {
        province.list.find(city => {
          if (city[compareKey] === cityName) {
            if (areaName) {
              city.list.find(area => {
                if (area[compareKey] === areaName) {
                  areaArr[2] = area[getKey];
                  return true;
                }
                return false;
              });
            }
            areaArr[1] = city[getKey];
            return true;
          } else {
            return false;
          }
        });
      }
      areaArr[0] = province[getKey];
      return true;
    } else {
      return false;
    }
  });
  return areaArr;
};

/**
 * 拿本地city的code 一条龙
 * @returns {Promise<unknown>}
 */
export const getCityCode = () => getCityName().then(cityKey2Key);

/**
 * 同步areas: [{provinceId: "28240", cityId: "28558", areaId: "28581"}] => ['深圳']
 * @param areas
 * @returns {BigInt64Array}
 */
export const getAreaNameSync = areas => areas.map(item => key2keySync([item.provinceId, item.cityId, item.areaId], 'name', 'id')).map(item => item[1] === '市辖区' ? item[0] : item[1]);
export const getAreaCityName = areas => getAreaList().then(() => getAreaNameSync(areas));
export const compareLocation = areas => getCityCode().then(arr => areas.find(item => item.provinceId === arr[0] && item.cityId === arr[1]));